package com.langChain4j.model.factory.impl;

import com.langChain4j.model.factory.AbsAgentLoader;
import com.langChain4j.api.vo.AgentChatVo;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.request.ChatRequest;
import dev.langchain4j.model.chat.request.ChatRequestParameters;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.model.chat.ChatModel;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;

/**
 * @author linjun
 * @date 2025/8/20 17:01
 * @description
 */
@Component("openAi")
public class OpenAiAgentLoader extends AbsAgentLoader {

    @Override
    public String chat(AgentChatVo chatVo) {
        ChatRequestParameters parameters = ChatRequestParameters.builder()
                .modelName(ObjectUtils.defaultIfNull(chatVo.getModelName(),"qwen1.5-0.5b-chat"))
                .temperature(ObjectUtils.defaultIfNull(chatVo.getTemperature(),1.0))
//                .maxOutputTokens(50)
                .build();
        ChatRequest chatRequest = ChatRequest.builder()
                .messages(UserMessage.from(chatVo.getMessage()))
                .parameters(parameters) // merges with and overrides default parameters
                .build();

        ChatModel chatModel = OpenAiChatModel.builder()
                .apiKey(OPENAI_API_KEY)
                .baseUrl(ObjectUtils.defaultIfNull(chatVo.getBaseUrl(),"https://dashscope.aliyuncs.com/compatible-mode/v1"))
                .logRequests(true)
                .build();

        ChatResponse chatResponse = chatModel.chat(chatRequest);
        return chatResponse.aiMessage().text();
    }

}
